<script setup>
import {defineAsyncComponent, ref} from "vue";
import {useForm} from "@inertiajs/vue3";
import useDialog from '@/composables/useDialog'
import useLoading from '@/composables/useLoading'
import useRequest from '@/composables/useRequest'
import {Message} from "@arco-design/web-vue";

const AvatarUpload = defineAsyncComponent(() => import('@/components/admin/upload/avatar.vue'));

const { FormRef, visible, mode, pk, actionName ,width} = useDialog()
const { loading, setLoading } = useLoading()

const {createApi, updateApi, showApi} = useRequest('admin.setting.permissions.accounts')

const emit = defineEmits(["success", "close"]);

const form = useForm({
    phone: '',
    name: '',
    email: '',
    avatar: '',
    password: '',
    confirm_password: '',
    status: 1,
    roles: '',
})

const handlePhone = (value, callback) => {
    if (!value) {
        callback(new Error('请输入注册手机号'))
        return false
    }
    if (!/^1[3456789]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号'))
        return false
    }
    callback()
}
const validatePassword = (value) =>
    /^(?=.*[A-Za-z])(?=.*\d).{6,16}$/.test(value) || '密码需6-16位且包含字母和数字'

const handleConfirmPassword = (value,callback) => {
    if(!value){
        callback(new Error('请输入确认密码'))
        return false
    }
    if (value !== form.password) {
        callback(new Error('两次密码不一致'))
        return false
    }
    callback()
}

const rules = ref({
    name: [{ required: true, message: '请输入账号名称' }],
    phone: [
        {required: true, length: 11, message: '请输入正确的手机号',validator:handlePhone, tigger: ['blur']},
    ],
    password: [
        {required: true, message: '请输入正确的密码',tigger: ['blur']},
        {required: true, message: '请输入密码长度6-16位', minLength: 6, maxLength: 16,tigger: ['blur']},
        {required: true, message: '请输入密码必须包含字母和数字', validator:validatePassword, tigger: ['blur']}
    ],
    confirm_password: [
        {required: true, message: '请输入确认密码', tigger: ['blur']},
        {required: true, message: '两次密码不一致', validator:handleConfirmPassword,tigger: ['blur']}
    ],
    avatar: [{ required: true, message: '请输入账号头像' }],
    status: [{required: true, message: '请选择账号状态'}],
    role_id: [{required: true, message: '请选择账号角色'}],
})


const handleSubmit = async () => {
    try {
        setLoading(true)
        const res = await FormRef.value?.validate()
        if (res) return false
        const apiMethod = mode.value === 'edit'
            ? () => updateApi(pk.value, form)
            : () => createApi(form)
        await apiMethod()
        Message.success(`${actionName.value}成功`)
        emit('success')
    } catch (error) {
        return false
    } finally {
        setLoading(false)
    }
}

const handleClose = () => {
    FormRef.value?.resetFields()
    form.reset()
    emit('close')
}

// 打开弹窗
const add = async () => {
    mode.value = 'add'
    visible.value = true
}

const edit = async (id) => {
    try {
        setLoading(true)
        pk.value = id
        const { data } = await showApi(id)
        Object.assign(form, data)
        rules.value = {
            ...rules.value,
            password: [],
            confirm_password: [],
        }
        mode.value = 'edit'
        visible.value = true
    } finally {
        setLoading(false)
    }
}

defineExpose({add, edit})
</script>
<template>
    <a-drawer
        v-model:visible="visible"
        :title="`账号${actionName}`"
        :loading="loading"
        :width
        @close="handleClose"
        @before-ok="handleSubmit"
    >
        <a-spin :loading="loading" class="w-full">


        <a-form ref="FormRef" :model="form" :rules auto-label-width>
            <a-form-item
                field="name"
                label="名称"
            >
                <a-input
                    v-model.trim="form.name"
                    :max-length="8"
                    allow-clear
                    placeholder="请输入账号名称"
                    show-word-limit
                />
            </a-form-item>

            <a-form-item
                field="phone"
                label="手机号"
            >
                <a-input
                    v-model.trim="form.phone"
                    :disabled="mode === 'edit'"
                    allow-clear
                    placeholder="请输入登录手机号"
                />
            </a-form-item>

            <a-form-item
                field="email"
                label="邮箱"
            >
                <a-input
                    v-model.trim="form.email"
                    allow-clear
                    placeholder="请输入邮箱"
                />
            </a-form-item>

            <a-form-item
                field="password"
                label="密码"
            >
                <a-input-password
                    v-model.trim="form.password"
                    allow-clear
                    placeholder="请输入登录密码"
                />
            </a-form-item>

            <a-form-item
                field="confirm_password"
                label="确认密码"
            >
                <a-input-password
                    v-model.trim="form.confirm_password"
                    allow-clear
                    placeholder="请输入确认密码"
                />
            </a-form-item>

            <a-form-item
                :rules="[{ required: true, message: '请上传用户头像' }]"
                field="avatar"
                label="用户头像"
            >
                 <avatar-upload v-model="form.avatar"  />
            </a-form-item>

            <a-form-item
                field="roles"
                label="用户角色"
            >
                <a-select v-model="form.roles" multiple placeholder="请选择管理员角色">
                    <a-option v-for="item in $page.props.options" :key="item.id" :value="item.id">
                        {{ item.name }}
                    </a-option>
                </a-select>
            </a-form-item>

            <a-form-item
                field="status"
                label="状态"
            >
                <a-radio-group v-model="form.status">
                    <a-radio :value="1">正常</a-radio>
                    <a-radio :value="0">禁用</a-radio>
                </a-radio-group>
            </a-form-item>
        </a-form>
        </a-spin>
    </a-drawer>
</template>

<style scoped>

</style>
